/*
 * @Author: csh
 * @Date: 2022-09-01
 * @LastEditors: csh
 * @LastEditTime: 2022-09-01
 * @Description: file content
 * @FilePath: /wochat-vue3-ts-pinia/src/webrtc/webrtc.device-control.ts
 */

class MediaDeviceControl {
  constructor() {
    this.deviceList = []
    this.options = {
      audioinput: {},
      videoinput: {},
      audiooutput: {}
    };
  }

  /** 
   * 获取设备列表
   */
  getMediaDevices() {
    return new Promise((resolve, reject) => {
      this.deviceList.splice(0);
      // 获取本地音视频设备列表
      webrtc.getDevices().then((deviceInfos) => {
        for (let i = 0; i < deviceInfos.length; i++) {
          let device = deviceInfos[i];
          // 为了兼容 WebRTC 的设备管理，将原有信息追加三个字段，供上层统一使用
          device.guid = device.deviceId
          device.alias = device.label
          device.type = this._webRTCKind2MediaType(device.kind)
          this.deviceList.push(device)
        }
        resolve(this.deviceList)
      });
    })
  };

  /**
   * 获取当前设置的媒体设备信息
   */
  getOptions() {
    return this.options;
  };

  getLocalCamera() {
    let constraints = { audio: false, video: true }
    return new Promise((resolve, reject) {
      navigator.getUserMedia(constraints, stream => {
        resolve(stream)
      }, err => {
        reject(err)
      })
    })
  }

  setSpeakerDevice(playDev) {
    this.options.audiooutput = playDev
  }
  setAudioCaptureDevice(captureDev) {
    this.options.audioinput = captureDev
  }
  setVideoCaptureDevice(captureDev) {
    this.options.videoinput = captureDev
  }

  _webRTCKind2MediaType(kind) {
    if (kind === "videoinput") {
      return 0
    } else if (kind === "audioinput") {
      return 2
    } else if (kind === "audiooutput") {
      return 3
    }
    return kind
  }
}


var mediaDeviceControl = new MediaDeviceControl()